<script setup>
import { ref, onUnmounted, onMounted } from 'vue'
import *as rrweb from 'rrweb'
import {
  startRecord,
  uploadRecord
} from '@/api/video'
import MD5 from '@/utils/canvasImei'

const id = ref('')
const events = ref([])
let timer = null

onMounted(async () => {
  window.addEventListener('beforeunload', async () => {
    await sendFile()
    clearInterval(timer)
    timer = null
  })
  id.value = `${MD5}_${new Date().getTime()}`
  await startVideo()
})


const startVideo = async () => {
  //请求开始分段接口
  const startRes = await startRecord(id.value)
  if (startRes.code !== 200) {
    console.log('startRes', startRes);
    return
  }
  events.value = []
  //在
  new rrweb.record({
    emit(event) {
      events.value.push(event)
    },
    recordCanvas: true,
    collectFonts: true,
  })
  sendFile()
  timer = setInterval(sendFile, 5 * 1000)
}


onUnmounted(async () => {
  await sendFile()
  clearInterval(timer)
  timer = null
})

const sendFile = async () => {
  if (timer) {
    const video_data = JSON.stringify(events.value)
    events.value = []
    const res = await uploadRecord(id.value, {
      data: video_data
    })
  }
}


</script>

<template>
  <RouterView />
</template>

<style scoped></style>
